import os,tempfile,shutil,commands
import pickle
import sys
import time
from crvclient import CRVClientTools

inf=open(sys.argv[1],"r")
clientconf=pickle.load(inf)
inf.close()

tool=CRVClientTools(clientconf)

#Definition: Active Role = Role that has ProfileProvided=True

#set last run to a very long time ago.
lastruntime=0

oufname="/var/log/crvclient.puppet.log"

#put the files in place
# now we have crvclient/certname.crt, certname.prk, certname.puk, pass.txt

while True:
    
    output=tool.doSecureStatusCurlUntilDone("getVMAttr?vmid=%s&name=RunUpdate"%(clientconf.vmid))
    if output=="None":
        RunUpdate=999999999
    else:
        RunUpdate=int(output)

    print "RunUpdate=%s"%(str(RunUpdate))

    currenttime=time.time()
    
    #if need to run
    if (currenttime-lastruntime)>RunUpdate:
    
        (error, warn)=tool.runPuppet()
#oufname)
        
        lastruntime=currenttime

        #set all active role to ProfileApplied=True
        if not error:
            tool.doSecureStatusCurlUntilDone("setVMActiveRoleSuccess?vmid=%s"%(clientconf.vmid))

        else:
            #do nothing and wait for next update and hope errors are fixed
            pass
        
    time.sleep(10)
    
